<?php
// $Id: simple_cart.checkout.inc,v 1.2 2011/01/25 18:16:14 vladsavitsky Exp $
/*
 * @file
 * simple_cart.checkout.inc Contain checkout form, form validator and submitter.
 */

/**
 * Checkout form.
 * If user has empty cart will redirect to cart page.
 *
 * @return array FAPI array that describe a checkout form.
 */
function simple_cart_checkout_form() {
  $cart_items = simple_cart_get_content_list();
  if ($cart_items) {
    $form['cart_items'] = array(
      '#type'         => 'fieldset',
      '#title'        => t('Cart content'),
      '#collapsible'  => TRUE,
      '#collapsed'    => TRUE,
    );
    $form['cart_items']['list'] = array(
      '#type'         => 'markup',
      '#value'        => theme('checkout_cart_items', $cart_items['items']),
    );
    // Checkout form:
    $form['name'] = array(
      '#type'         => 'textfield',
      '#title'        => t('Name'),
      '#required'     => TRUE,
      '#default_value' => $_SESSION['simple_cart_customers_name'],
    );
    $form['phone'] = array(
      '#type'         => 'textfield',
      '#title'        => t('Phone'),
      '#required'     => TRUE,
      '#default_value' => $_SESSION['simple_cart_customers_phone'],
    );
    $form['email'] = array(
      '#type'         => 'textfield',
      '#title'        => t('E-mail'),
      '#required'     => TRUE,
      '#default_value' => $_SESSION['simple_cart_customers_email'],
    );
    $form['comment'] = array(
      '#type'         => 'textarea',
      '#title'        => t('Comment'),
    );
    $form['back_to_cart'] = array(
      '#type'           => 'button',
      '#name'           => 'back_to_cart',
      '#value'          => t('Back to cart'),
    );
    $form['checkout'] = array(
      '#type'           => 'submit',
      '#name'           => 'order',
      '#value'          => t('Order'),
    );
    return $form;
  }
  else {
    // Cart is empty and Checkout page shouldn't be shown. Redirect to cart:
    drupal_goto('cart');
  }
}

function simple_cart_checkout_form_validate($form, $form_state) {
  $op = $form_state['clicked_button']['#name'];
  switch ($op) {
    case 'back_to_cart':
      drupal_goto('cart');
      break;
    case 'order':
      // Check email field:
      if (!valid_email_address($form_state['values']['email'])) {
        form_set_error('email', t('The email address appears to be invalid.'));
      }
      if (!_simple_cart_valid_phone($form_state['values']['phone'])) {
        form_set_error('phone', t('The phone appears to be invalid.'));
      }
      break;
  }
}

function simple_cart_checkout_form_submit($form, $form_state) {
  $op = $form_state['clicked_button']['#name'];
  switch ($op) {
    case 'order':
      // Validation has been passed - empty cart and redirect to front-page:
      $values = $form_state['values'];
      $variables = array(
        '@customers_name'     => check_plain($values['name']),
        '@customers_email'    => check_plain($values['email']),
        '@customers_phone'    => check_plain($values['phone']),
        '@customers_comment'  => check_plain($values['comment']),
        '!sitename'           => check_plain(variable_get('site_name', 'Drupal')),
        '!items_list'         => theme('email_cart_items', 'customer_email'),
      );
      // Save user's data into session:
      $_SESSION['simple_cart_customers_name']  = check_plain($values['name']);
      $_SESSION['simple_cart_customers_email'] = check_plain($values['email']);
      $_SESSION['simple_cart_customers_phone'] = check_plain($values['phone']);
      $error = FALSE;
      // =====================================================================
      // First email to customer:
      $params = array();
      $subject = t(variable_get('simple_cart_customer_subject', "Your order at !sitename"), $variables);
      $body = t(variable_get('simple_cart_customer_body', "Hello @customers_name!\n\n You have ordered recently at !sitename this items:\n\n!items_list\n\nOur managers was recieved your order and process it as soon as posible."), $variables);

      $params['body'] = $body;
      $params['subject'] = $subject;
      $params['from'] = variable_get('site_mail', '');
      $params['from_name'] = $variables['!sitename'];

      $mail_key = 'simple-cart-customer-email';
      $email = $variables['@customers_email'];
      $result = drupal_mail('simple_cart', $mail_key, $email, user_preferred_language($user), $params);
      if ($result['result'] !== TRUE) {
        $error = TRUE;
        $status[$email] = $result['result'];
      }
      // =====================================================================
      // Second email to managers
      //
      $variables['!items_list'] = theme('email_cart_items', 'manager_email');
      $params = array();
      $subject = t(variable_get('simple_cart_manager_subject', "Order at !sitename"), $variables);
      $body = t(variable_get('simple_cart_manager_body', "Customer @customers_name have ordered at !sitename this items:\n\n!items_list\n\nCustomer provide this contact information:\n\nName: @customers_name\n\nEmail: @customers_email\n\nPhone: @customers_phone\n\nCustomers comment:\n\n===================================================\n\n@customers_comment\n\n==================================================="), $variables);

      $params['body'] = $body;
      $params['subject'] = $subject;
      $params['from'] = variable_get('site_mail', '');
      $params['from_name'] = $variables['!sitename'];

      $mail_key = 'simple-cart-manager-email';

      $manager_emails = explode("\n", variable_get('simple_cart_manager_emails', ''));
      foreach ($manager_emails as $email) {
        $result = drupal_mail('simple_cart', $mail_key, trim($email), user_preferred_language($user), $params);
        if ($result['result'] !== TRUE) {
          $error = TRUE;
          $status[$email] = $result['result'];
        }
      }
      // =====================================================================
      // Check total result:
      if ($error) {
        foreach ($status as $email => $result) {
          if (!$result) {
            watchdog('simple_cart', t("Can't send email to @email.", array('@email' => $email)));
          }
          else {
            watchdog('simple_cart', t("Successfully sent email to @email.", array('@email' => $email)));
          }
        }
        drupal_set_message(t("Can't process your order. Please, try again."), 'error');
        drupal_goto('cart');
      }
      else {
        drupal_set_message(t("You order has been sent to our managers and they will contact you as soon as posible."));
        simple_cart_empty();
        drupal_goto('<front>');
      }
      break;
  }
}

/**
 * Do validation of phone number
 *
 * @param string $phone
 * @return boolean Returns TRUE if phone is valid. Returns FALSE if not valid.
 */
function _simple_cart_valid_phone($phone) {
  if (!$phone) return FALSE;
  // Leave only numbers:
  $phone_number = preg_replace("/[^0-9]/", "", $phone);
  if (drupal_strlen($phone_number)) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}
